package com.lastcrdg.pieview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import java.util.List;

/**
 * author：liluo
 * e-mail：lastcrazysun@163.com
 * company：cusc
 * date：2017/9/28 9:06
 * description：
 */

public class PieView extends View {

    private Paint mPaint = new Paint();
    private RectF mRectF;
    private int width;
    private int height;
    private float sum;
    private List<Bean> mList;
    private float startAngel = 0;
    private int[] colors = {0xFFCCFF00, 0xFF6495ED, 0xFFE32636, 0xFF800000, 0xFF808000, 0xFFFF8C69, 0xFF808080,
            0xFFE6B800, 0xFF7CFC00};
    private float mR;

    public PieView(Context context) {
        super(context);
    }

    public PieView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAntiAlias(true);
        mPaint.setTextSize(48);
    }

    private void initPaint(int color) {
        mPaint.setColor(color);
    }

    public PieView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = MeasureSpec.getSize(widthMeasureSpec);
        height = MeasureSpec.getSize(heightMeasureSpec);
        mR = (float) (Math.min(width, height) * 0.8) / 2;
        mRectF = new RectF(-mR, -mR, mR, mR);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.translate(width / 2, height / 2);
        if (mList != null) {
            for (int i = 0; i < mList.size(); i++) {
                initPaint(mList.get(i).getColor());
                canvas.drawArc(mRectF, startAngel, mList.get(i).getAngel(), true, mPaint);
                startAngel += mList.get(i).getAngel();
                float x = (float) (mR * 1.2 );
                float y = (float) (mR * 1.2 );
                canvas.rotate(mList.get(i).getAngel()/2);
                canvas.drawText(mList.get(i).getNumber() + "", x, y, mPaint);
            }
        }
    }

    public void setData(List<Bean> data) {
        mList = data;
        for (int i = 0; i < data.size(); i++) {
            sum += data.get(i).getNumber();
            data.get(i).setColor(colors[i]);
        }

        for (Bean bean : data) {
            bean.setAngel(bean.getNumber() / sum * 360);
        }
        invalidate();
    }

}
